/*
 * Copyright (c) 2018-2999 九五云信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.multishop.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Maps;
import com.yami.shop.bean.enums.OfflineHandleEventType;
import com.yami.shop.bean.enums.SendType;
import com.yami.shop.bean.model.OfflineHandleEvent;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.bean.param.ShopDetailParam;
import com.yami.shop.bean.param.OfflineHandleEventAuditParam;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.service.OfflineHandleEventService;
import com.yami.shop.service.ShopDetailService;
import com.yami.shop.service.SmsLogService;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.Objects;


/**
 * @author lgh on 2018/08/29.
 */
@Controller
@RequestMapping("/shop/shopDetail")
public class ShopDetailController {

    @Autowired
    private ShopDetailService shopDetailService;

    @Autowired
    private MapperFacade mapperFacade;

//    @Autowired
//    private ShopAuditingService shopAuditingService;

    @Autowired
    private OfflineHandleEventService offlineHandleEventService;

    @Autowired
    private  SmsLogService smsLogService;


    /**
     * 修改分销开关
     */
    @PutMapping("/isDistribution")
    public ResponseEntity<Void> updateIsDistribution(@RequestParam Integer isDistribution) {
        ShopDetail shopDetail = new ShopDetail();
        shopDetail.setShopId(SecurityUtils.getShopUser().getShopId());
        shopDetail.setIsDistribution(isDistribution);
        shopDetailService.updateById(shopDetail);
        // 更新完成后删除缓存
        shopDetailService.removeShopDetailCacheByShopId(shopDetail.getShopId());
        return ResponseEntity.ok().build();
    }

    /**
     * 获取信息
     */
    @GetMapping("/info")
    public ResponseEntity<ShopDetail> info() {
        ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(SecurityUtils.getShopUser().getShopId());
        return ResponseEntity.ok(shopDetail);
    }

    /**
     * 分页获取
     */
    @GetMapping("/page")
    public ResponseEntity<IPage<ShopDetail>> page(PageParam<ShopDetail> page) {
        ShopDetail shopDetail = new ShopDetail();
        shopDetail.setUserId(SecurityUtils.getShopUser().getUserId());
        IPage<ShopDetail> shopDetails = shopDetailService.page(page,
                new LambdaQueryWrapper<ShopDetail>()
                        .like(StrUtil.isNotBlank(shopDetail.getShopName()), ShopDetail::getShopName, shopDetail.getShopName())
                        .eq(shopDetail.getUserId() != null, ShopDetail::getUserId, shopDetail.getUserId())
                        .orderByDesc(ShopDetail::getShopId));
        return ResponseEntity.ok(shopDetails);
    }

    /**
     * 修改店铺信息
     */
    @PutMapping
    public ResponseEntity<Void> update(@Valid @RequestBody ShopDetailParam shopDetailParam) {
        int count = shopDetailService.count(new LambdaQueryWrapper<ShopDetail>().eq(ShopDetail::getShopName, shopDetailParam.getShopName())
                .eq(ShopDetail::getShopStatus,1).ne(ShopDetail::getShopId, SecurityUtils.getShopUser().getShopId()));
        if (count > 0) {
            // 已有相同名称
            throw new YamiShopBindException("yami.shop.name.have.already");
        }
        ShopDetail dbShopDetail = shopDetailService.getShopDetailByShopId(SecurityUtils.getShopUser().getShopId());
        ShopDetail shopDetail = mapperFacade.map(shopDetailParam, ShopDetail.class);
        shopDetail.setShopId(SecurityUtils.getShopUser().getShopId());
        shopDetail.setUpdateTime(new Date());
        shopDetailService.updateShopDetail(shopDetail, dbShopDetail);
        return ResponseEntity.ok().build();
    }

    /**
     * 修改店铺接收手机号
     */
    @PutMapping("/updateMobile")
    public ResponseEntity<Void> updateMobile(@RequestBody ShopDetail shopDetail) {
        shopDetail.setShopId(SecurityUtils.getShopUser().getShopId());
        shopDetail.setUpdateTime(new Date());
        shopDetailService.updateShopDetail(shopDetail,null);
        return ResponseEntity.ok().build();
    }

    /**
     * 通过活动id获取下线信息
     */
    @GetMapping("/getOfflineHandleEventByShopId/{shopId}")
    public ResponseEntity<OfflineHandleEvent> getOfflineHandleEventByShopId(@PathVariable("shopId") Long shopId) {
        OfflineHandleEvent offlineHandleEvent = offlineHandleEventService.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.SHOP.getValue(), shopId);
        return ResponseEntity.ok(offlineHandleEvent);
    }

    /**
     * 违规商品提交审核
     */
    @PostMapping("/auditApply")
    public ResponseEntity<Void> auditApply(@RequestBody OfflineHandleEventAuditParam offlineHandleEventAuditParam) {
        ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(offlineHandleEventAuditParam.getHandleId());
        if (shopDetail == null) {
            // 未找到该店铺信息
            throw new YamiShopBindException("yami.store.not.exist");
        }
        shopDetailService.auditApply(offlineHandleEventAuditParam.getEventId(), offlineHandleEventAuditParam.getHandleId(), offlineHandleEventAuditParam.getReapplyReason());
        return ResponseEntity.ok().build();
    }

    /**
     * 发送验证码接口
     */
    @PostMapping("/sendCode")
    public ResponseEntity<String> sendLoginCode() {
        ShopDetail shopDetail = shopDetailService.getById(SecurityUtils.getShopUser().getShopId());
//        if(Objects.equals(shopDetail.getShopId(), Constant.MAIN_SHOP)){
//            throw  new YamiShopBindException("自营店无法提现");
//        }
        // 每个ip每分钟只能发十个注册的验证码，免得接口被利用
        if(Objects.equals(shopDetail.getShopId(), Constant.MAIN_SHOP)){
            // 自营店无法提现
            throw  new YamiShopBindException("yami.my.store.no.cash");
        }
        smsLogService.sendSms(SendType.VALID, shopDetail.getShopId().toString(), shopDetail.getMobile(), Maps.newHashMap());
        return ResponseEntity.ok(shopDetail.getMobile());
    }

}
